﻿using NLog.Config;
using NLog.Targets;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Leo.Common.Logger
{
    /// <summary>
    /// 日志配置器
    /// </summary>
    public static class NLogConfigurator
    {
        // 默认配置文件路径
        private const string DefaultConfigPath = "nlog.config";

        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init(string? configPath = null)
        {
            configPath ??= DefaultConfigPath;
            //if (LogManager.Configuration is not null)
            //{
            //    return;
            //}

            try
            {
                //加载外部配置文件
                if (File.Exists(configPath))
                {
                    LogManager.Setup().LoadConfigurationFromFile(configPath, optional: false);
                }
                else
                {
                    SetupDefaultConfiguration();
                    LogManager.GetCurrentClassLogger().Warn($"未找到配置文件: {configPath}, 已启用默认配置");
                }
            }
            catch (Exception ex)
            {
                SetupDefaultConfiguration();
                LogManager.GetCurrentClassLogger().Error(ex, "日志配置初始化失败");
            }
        }


        /// <summary>
        /// 创建默认配置
        /// </summary>
        private static void SetupDefaultConfiguration()
        {
            //生成默认配置
            var config = new LoggingConfiguration();

            // 控制台目标
            var consoleTarget = new ConsoleTarget("console")
            {
                Layout = "${longdate}||${level}||${logger}||${message}${exception:format=ToString}"
            };
            config.AddRule(LogLevel.Info, LogLevel.Fatal, consoleTarget);

            // 文件目标
            var fileTarget = new FileTarget("file")
            {
                FileName = "${basedir}/logs/${shortdate}.log",
                Layout = "${longdate}||${level}||${logger}||${message}${exception:format=ToString}",
                ArchiveEvery = FileArchivePeriod.Day,
                MaxArchiveFiles = 7
            };
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);

            LogManager.Configuration = config;
        }



        /// <summary>
        /// 自定义配置（高级用法）
        /// </summary>
        public static void Configure(Action<LoggingConfiguration> configAction)
        {
            LogManager.Configuration ??= new LoggingConfiguration();
            configAction?.Invoke(LogManager.Configuration);
            LogManager.ReconfigExistingLoggers();
        }


    }
}
